package com.aierjun.ani.init;

import android.app.Application;
import android.os.Environment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Ani_aierJun on 2017/9/29.
 */

public class UncaughtExceptionUtils {

    public static void init(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
        Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
    }

    public static void set(Application application, String dirName, Throwable throwable) {
        // 将错误日志写在 mnt/sdcard/test/error.log
        File errLog = new File(getFilePath(dirName) + "error.txt");
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream(errLog, true));
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .format(new Date(System.currentTimeMillis()));
            printStream.println("**********" + format + "**********");
            throwable.printStackTrace(printStream);
            printStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // TODO 将日志文件上传到服务器
        // 强制让应用退出
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    private static String getFilePath(String name) {
        StringBuffer buffer = new StringBuffer();
        String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + name + "/";
        buffer.append(sdCardPath);
        buffer.append(File.separator);
        buffer.append("log");
        buffer.append(File.separator);

        if (createFile(buffer.toString())) {
            return buffer.toString();
        } else {
            return null;
        }
    }

    private static boolean createFile(String path) {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            return file.mkdirs();
        }
        return true;
    }
}
